package com.lk.spring.boot.sample.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/**
 * 配置sqlSessionFactory 
* <p>Title:MybatisConfig </p>
* <p>Description: </p>
* <p>Company: </p> 
* @author kexl
* @date 上午10:52:23
 */
@Configuration
public class MybatisConfig implements TransactionManagementConfigurer{ //实现TransactionManagementConfigurer接口，配置spring事务的管理； 

	@Autowired
	private DataSource dataSource;//注入datasource； 
	
	@Bean(name="sqlSessionFactory")//注入的名称指定，如果不指定，默认方法名为bean的名字，命名规则需要遵守spring命名规范；
	public SqlSessionFactory SqlSessionFactoryBean(){
		org.mybatis.spring.SqlSessionFactoryBean bean=new org.mybatis.spring.SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setTypeAliasesPackage("com.lk.spring.boot.sample.bean");
		//分页插件
//      PageHelper pageHelper = new PageHelper();
//      Properties properties = new Properties();
//      properties.setProperty("reasonable", "true");
//      properties.setProperty("supportMethodsArguments", "true");
//      properties.setProperty("returnPageInfo", "check");
//      properties.setProperty("params", "count=countSql");
//      pageHelper.setProperties(properties);
      //添加插件
//      bean.setPlugins(new Interceptor[]{pageHelper});
		//
		ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
		
		try {
			bean.setMapperLocations(resolver.getResources("classpath:/mybatis/*Mapper.xml"));
			return bean.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	@Bean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){
		return new SqlSessionTemplate(sqlSessionFactory);
	}
	@Bean
	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(dataSource);
	}

}
